#!/usr/bin/env perl
#-----------------------------------------------------------------------------------------------
#
# build-namelist
#
# This script builds the namelists for the MPASSI configuration of E3SM.
#
# build-namelist uses a config_cache.xml file that current contains the seaice grid information.
# build-namelist reads this file to obtain information it needs to provide
# default values that are consistent with the MPASSI XML file.  For example, the grid resolution
# is obtained from the cache file and used to determine appropriate defaults for namelist input
# that is resolution dependent.
#
# The simplest use of build-namelist is to execute it from the build directory where configure
# was run.  By default it will use the config_cache.xml file that was written by configure to
# determine the build time properties of the executable, and will write the files that contain
# the output namelists in that same directory.
#
#
# Date        Contributor      Modification
# -------------------------------------------------------------------------------------------
# 2015-08-21  Jon Wolfe        Original version
#--------------------------------------------------------------------------------------------
use strict;
use Cwd qw(getcwd abs_path);
use English;
use Getopt::Long;
use IO::File;

#-----------------------------------------------------------------------------------------------

sub usage {
    die <<EOF;
SYNOPSIS
     build-namelist [options]
OPTIONS
     -infile "filepath"    Specify a file containing namelists to read values from.
     -namelist "namelist"  Specify namelist settings directly on the commandline by supplying
                           a string containing FORTRAN namelist syntax, e.g.,
                              -namelist "&mpas-seaice_nml dt=1800 /"
     -help [or -h]         Print usage to STDOUT.
     -test                 Enable checking that input datasets exist on local filesystem.
     -verbose              Turn on verbose echoing of informational messages.
     -caseroot             CASEROOT directory variable
     -casebuild            CASEBUILD directory variable
     -cimeroot             CIMEROOT directory variable
     -ice_grid             ICE_GRID variable
     -decomp_prefix        decomp_prefix variable
     -date_stamp           date_stamp variable
     -cfg_grid             Directory containing MPASSI configuration scripts.
                           If not defined, location is set as \$ProgDir or \$cwd
                           (Needed to run build-namelist from SourceMods dir)
     -inst_string          inst_string variable
     -ice_ic_mode          variable for initial condition file mode
                           Options are: spunup, cold_start
     -ice_bgc              variable for enabling sea ice BGC
     -surface_mode         variable for surface mode
                           Options are: free, non-free
     -iceberg_mode         variable for iceberg mode
                           Options are: none, data, prognostic
     -prognostic_mode      variable for prognostic mode
                           Options are: full, prescribed
     -column_mode          variable for column-only mode
                           Options are: true, false
     -ntasks_ice           NTASKS_ICE for this case
     -ninst_ice            NINST_ICE for this case

NOTE: The precedence for setting the values of namelist variables is (highest to lowest):
      1. namelist values set by specific command-line options, i.e. (none right now)
      2. values set on the command-line using the -namelist option,
      3. values read from the file specified by -infile,
      4. values from the namelist defaults file - or values specifically set in build-namelist
EOF
}

#-----------------------------------------------------------------------------------------------
# Set the directory that contains the MPASSI configuration scripts.  If the command was
# issued using a relative or absolute path, that path is in $ProgDir.  Otherwise assume the
# command was issued from the current working directory.

(my $ProgName = $0) =~ s!(.*)/!!;      # name of this script
my $ProgDir = $1;                      # name of directory containing this script -- may be a
                                       # relative or absolute path, or null if the script is in
                                       # the user's PATH
my $cwd = getcwd();                    # current working directory
my $cfgdir;                            # absolute pathname of directory that contains this script
if ($ProgDir) {
    $cfgdir = absolute_path($ProgDir);
} else {
    $cfgdir = $cwd;
}

#-----------------------------------------------------------------------------------------------

# Process command-line options.

my %opts = ( help            => 0,
             test            => 0,
             verbose         => 0,
             preview         => 0,
             caseroot        => undef,
             casebuild       => undef,
             cimeroot        => undef,
             inst_string     => undef,
             ice_grid        => undef,
             decomp_prefix   => undef,
             date_stamp      => undef,
             ice_ic_mode     => undef,
             ice_bgc         => undef,
             surface_mode    => undef,
             iceberg_mode    => undef,
             prognostic_mode => undef,
             column_mode => undef,
             cfg_dir         => $cfgdir,
             ntasks_ice      => 0,
             ninst_ice       => 0,
           );

GetOptions(
    "h|help"            => \$opts{'help'},
    "infile=s"          => \$opts{'infile'},
    "namelist=s"        => \$opts{'namelist'},
    "v|verbose"         => \$opts{'verbose'},
    "caseroot=s"        => \$opts{'caseroot'},
    "casebuild=s"       => \$opts{'casebuild'},
    "cimeroot=s"        => \$opts{'cimeroot'},
    "inst_string=s"     => \$opts{'inst_string'},
    "ice_grid=s"        => \$opts{'ice_grid'},
    "decomp_prefix=s"   => \$opts{'decomp_prefix'},
    "date_stamp=s"      => \$opts{'date_stamp'},
    "ice_ic_mode=s"     => \$opts{'ice_ic_mode'},
    "ice_bgc=s"         => \$opts{'ice_bgc'},
    "surface_mode=s"    => \$opts{'surface_mode'},
    "iceberg_mode=s"    => \$opts{'iceberg_mode'},
    "prognostic_mode=s" => \$opts{'prognostic_mode'},
    "column_mode=s"     => \$opts{'column_mode'},
    "cfg_dir=s"         => \$opts{'cfg_dir'},
    "preview"           => \$opts{'preview'},
    "ntasks_ice=i"      => \$opts{'ntasks_ice'},
    "ninst_ice=i"       => \$opts{'ninst_ice'},
)  or usage();

# Give usage message.
usage() if $opts{'help'};

# Check for unparsed arguments
if (@ARGV) {
    print "ERROR: unrecognized arguments: @ARGV\n";
    usage();
}

# Define print levels:
# 0 - only issue fatal error messages
# 1 - only informs what files are created (currently not used)
# 2 - verbose
my $print = 0;
my $preview = 0;
if ($opts{'verbose'}) { $print = 2; }
if ($opts{'preview'}) { $preview = 1; }
my $eol = "\n";

if ($print>=2) { print "Setting MPASSI configuration script directory to $cfgdir$eol"; }

my $CASEROOT        = $opts{'caseroot'};
my $CASEBUILD       = $opts{'casebuild'};
my $CIMEROOT        = $opts{'cimeroot'};
my $inst_string     = $opts{'inst_string'};
my $ICE_GRID        = $opts{'ice_grid'};
my $decomp_prefix   = $opts{'decomp_prefix'};
my $date_stamp      = $opts{'date_stamp'};
my $ice_ic_mode     = $opts{'ice_ic_mode'};
my $ice_bgc         = $opts{'ice_bgc'};
my $surface_mode    = $opts{'surface_mode'};
my $iceberg_mode    = $opts{'iceberg_mode'};
my $prognostic_mode = $opts{'prognostic_mode'};
my $column_mode     = $opts{'column_mode'};
my $NINST_ICE       = $opts{'ninst_ice'};
my $NTASKS_ICE      = $opts{'ntasks_ice'};
$cfgdir             = $opts{'cfg_dir'};

my $CIMEROOT;
if ( defined $opts{'cimeroot'} ) {
    $CIMEROOT = $opts{'cimeroot'};
}


# Validate some of the commandline option values.
validate_options("commandline", \%opts);

# build config_cache.xml file (needed below)
my $config_cache = "${CASEBUILD}/mpassiconf/config_cache.xml";
my  $fh = new IO::File;
$fh->open(">$config_cache") or die "** can't open file: $config_cache\n";
print $fh  <<"EOF";
<?xml version="1.0"?>
<config_definition>
<entry id="ice_grid" value="$ICE_GRID">
<entry id="prognostic_mode" value="$prognostic_mode">
<entry id="column_mode" value="$column_mode">
<entry id="decomp_prefix" value="$decomp_prefix">
<entry id="date_stamp" value="$date_stamp">
</config_definition>
EOF
$fh->close;
if ($print>=2) { print "Wrote file $config_cache $eol"; }
(-f "config_cache.xml")  or  die <<"EOF";
** $ProgName - Cannot find configuration cache file: config_cache.xml\" **
EOF

#-----------------------------------------------------------------------------------------------
# Make sure we can find required perl modules, definition, and defaults files.
# Look for them under the directory that contains the configure script.

# The root directory for the input data files must be specified.

my $srcroot = abs_path("$CIMEROOT/../");
if (! -d "$srcroot") {
    die "** Invalid SRCROOT directory: $srcroot ** ";
}

print "SRCROOT IS: $srcroot\n";

my $perl5lib = "$CIMEROOT/utils/perl5lib";
if (! -d "$perl5lib") {
    die "** Invalid perl5lib root directory: $perl5lib ** ";
}

# The Build::Config module provides utilities to access the configuration information
# in the config_cache.xml file (see below)
(-f "$perl5lib/Build/Config.pm")  or  die <<"EOF";
** $ProgName - Cannot find perl module \"Build/Config.pm\" in directory \"$perl5lib\" **
EOF

# The Build::NamelistDefinition module provides utilities to validate that the output
# namelists are consistent with the namelist definition file
(-f "$perl5lib/Build/NamelistDefinition.pm")  or  die <<"EOF";
** $ProgName - Cannot find perl module \"Build/NamelistDefinition.pm\" in directory \"$perl5lib\" **
EOF

# The Build::NamelistDefaults module provides a utility to obtain default values of namelist
# variables based on finding a best fit with the attributes specified in the defaults file.
(-f "$perl5lib/Build/NamelistDefaults.pm")  or  die <<"EOF";
** $ProgName - Cannot find perl module \"Build/NamelistDefaults.pm\" in directory \"$perl5lib\" **
EOF

# The Build::Namelist module provides utilities to parse input namelists, to query and modify
# namelists, and to write output namelists.
(-f "$perl5lib/Build/Namelist.pm")  or  die <<"EOF";
** $ProgName - Cannot find perl module \"Build/Namelist.pm\" in directory \"$perl5lib\" **
EOF

# The namelist definition file contains entries for all namelist variables that
# can be output by build-namelist.  The version of the file that is associate with a
# fixed MPASSI tag is $cfgdir/namelist_files/namelist_definition.xml.  To aid developers
# who make use of the SourceMods/src.mpassi directory - we allow the definition file
# to come from that directory
my $nl_definition_file;
if (-f "${CASEROOT}/SourceMods/src.mpassi/namelist_definition_mpassi.xml") {
    $nl_definition_file = "${CASEROOT}/SourceMods/src.mpassi/namelist_definition_mpassi.xml";
}
if (! defined $nl_definition_file) {
    # default location of namelist definition file
    $nl_definition_file = "$cfgdir/namelist_files/namelist_definition_mpassi.xml";
    (-f "$nl_definition_file")  or  die <<"EOF";
    ** $ProgName - ERROR: Cannot find namelist definition file \"$nl_definition_file\" **
EOF
}
if ($print>=2) { print "Using namelist definition file $nl_definition_file$eol"; }

# The namelist defaults file contains default values for all required namelist variables.
my $nl_defaults_file;
if (-f "${CASEROOT}/SourceMods/src.mpassi/namelist_defaults_mpassi.xml") {
    $nl_defaults_file = "${CASEROOT}/SourceMods/src.mpassi/namelist_defaults_mpassi.xml";
}
if (! defined $nl_defaults_file) {
    $nl_defaults_file = "$cfgdir/namelist_files/namelist_defaults_mpassi.xml";
    (-f "$nl_defaults_file")  or  die <<"EOF";
    ** $ProgName - Cannot find namelist defaults file \"$nl_defaults_file\" **
EOF
}
if ($print>=2) { print "Using namelist defaults file $nl_defaults_file$eol"; }

#-----------------------------------------------------------------------------------------------
# Add $perl5lib_dir to the list of paths that Perl searches for modules
unshift @INC, "$perl5lib";
#require XML::Lite;
require Build::Config;
require Build::NamelistDefinition;
require Build::NamelistDefaults;
require Build::Namelist;
require Config::SetupTools;

#-----------------------------------------------------------------------------------------------
# Create a configuration object from the MPASSI config_cache.xml file-  created by
# mpassi.cpl7.template in $CASEBUILD/mpassiconf
my $cfg = Build::Config->new('config_cache.xml');

# Create a namelist definition object.  This object provides a method for verifying that the
# output namelist variables are in the definition file, and are output in the correct
# namelist groups.
my $definition = Build::NamelistDefinition->new($nl_definition_file);

# Create a namelist defaults object.  This object provides default values for variables
# contained in the input defaults file.  The configuration object provides attribute
# values that are relevent for the MPASSI library for which the namelist is being produced.
my $defaults = Build::NamelistDefaults->new($nl_defaults_file, $cfg);

# Create an empty namelist object.  Add values to it in order of precedence.
my $nl = Build::Namelist->new();

#-----------------------------------------------------------------------------------------------
# Process the user input in order of precedence.  At each point we'll only add new
# values to the namelist and not overwrite previously specified specified values which
# have higher precedence.

# Process the commandline args that provide specific namelist values.

# Process the -namelist arg.
if (defined $opts{'namelist'}) {
    # Parse commandline namelist
    my $nl_arg = Build::Namelist->new($opts{'namelist'});

    # Validate input namelist -- trap exceptions
    my $nl_arg_valid;
    eval { $nl_arg_valid = $definition->validate($nl_arg); };
    if ($@) {
      die "$ProgName - ERROR: Invalid namelist variable in commandline arg '-namelist'.\n $@";
    }

    # Merge input values into namelist.  Previously specified values have higher precedence
    # and are not overwritten.
    $nl->merge_nl($nl_arg_valid);
}

# Process the -infile arg.
if (defined $opts{'infile'}) {
    # Parse namelist input from a file
    my $nl_infile = Build::Namelist->new($opts{'infile'});
    my $nl_infile_valid = Build::Namelist->new();

    # Validate namelist variables (going to do this one variable at a time)
    for my $group ($nl_infile->get_group_names()) {
      for my $var ($nl_infile->get_variable_names($group)) {
        my $var_local; # Name of variable to write to infile
        my $nl_check_var = Build::Namelist->new();
        my $nl_check_valid;
        my $val = $nl_infile->get_variable_value($group, $var);
        my @broken = split(/&/,$var);
        my $check_grp = 0; # If 1, make sure group found in definitions file
                           # matches that specified in user_nl_mpassi

        # if variable has ampersand, truncate it unless it is type derived
        if ($broken[1]) {
          my $nl_check_amp = Build::Namelist->new();
          $nl_check_amp->set_variable_value($group, $var, $val);
          eval { $definition->validate($nl_check_amp) };
          if (not $@) {
            # & is required in variable name
            $var_local = $var;
          } else {
            # & should not be in variable name
            $var_local = $broken[0];
            $check_grp = 1;
          }
        } else {
          $var_local = $var;
        }

        # Make sure variable is defined in namelist_definition_mpassi.xml
        $nl_check_var->set_variable_value($group, $var_local,$val);
        eval { $nl_check_valid = $definition->validate($nl_check_var); };
        (not $@) or die <<"EOF";
** ERROR: either $var_local is not a valid MPASSI namelist variable or $var_local = $val is not a valid value; please fix user_nl_mpassi. Note that $var_local may appear in multiple namelists, in which case you need to specify the correct namelist in user_nl_mpassi using the format $var_local\&namelist_nml = $val, where \&namelist_nml is the mpassi_in namelist containing $var_local.**
EOF

        # If group was specified in user_nl_mpassi, make sure it matches
        # the group in the definitions file.
        my @group_valid = $nl_check_valid->get_group_names();
        ((not $check_grp) or ($broken[1] eq $group_valid[0])) or die <<"EOF";
** ERROR: $broken[0] is in $group_valid[0], not $broken[1]! Please fix this in user_nl_mpassi. **
EOF

        # Add variable to validated namelist
        $nl_infile_valid->set_variable_value($group_valid[0], $var_local, $val);
      }
    }

    # If preview is desired and something has been changed in $nl_infile_valid,
    # output everything in $nl_infile_valid
    if (($preview == 1) && ($nl_infile_valid->get_group_names)) {
      print " - The following values have been set in user_nl_mpassi:\n";
      print_nl_to_screen($nl_infile_valid);
    }
    # Merge input values into namelist.  Previously specified values have higher
    # precedence and are not overwritten.
    $nl->merge_nl($nl_infile_valid);
}

#-----------------------------------------------------------------------------------------------
# Determine xml variables
#unshift @INC, "$CASEROOT/Tools";
#require XML::Lite;
#require SetupTools;

my %xmlvars = ();
SetupTools::getxmlvars($CASEROOT, \%xmlvars);
foreach my $attr (keys %xmlvars) {
  $xmlvars{$attr} = SetupTools::expand_xml_var($xmlvars{$attr}, \%xmlvars);
}

my $RUNDIR                 = "$xmlvars{'RUNDIR'}";
my $CODEROOT               = "$xmlvars{'CODEROOT'}";
my $DIN_LOC_ROOT           = "$xmlvars{'DIN_LOC_ROOT'}";
my $CASE                   = "$xmlvars{'CASE'}";
my $CALENDAR               = "$xmlvars{'CALENDAR'}";
my $NCPL_BASE_PERIOD       = "$xmlvars{'NCPL_BASE_PERIOD'}";
my $ICE_NCPL               = "$xmlvars{'ICE_NCPL'}";
my $ICE_COUPLING           = "$xmlvars{'ICE_COUPLING'}";
my $INFO_DBUG              = "$xmlvars{'INFO_DBUG'}";
my $RUN_TYPE               = "$xmlvars{'RUN_TYPE'}";
my $RUN_STARTDATE          = "$xmlvars{'RUN_STARTDATE'}";
my $START_TOD              = "$xmlvars{'START_TOD'}";
my $RUN_REFDATE            = "$xmlvars{'RUN_REFDATE'}";
my $CONTINUE_RUN           = "$xmlvars{'CONTINUE_RUN'}";

my $SSTICE_GRID_FILENAME;
my $SSTICE_DATA_FILENAME;
my $SSTICE_YEAR_ALIGN;
my $SSTICE_YEAR_START;
my $SSTICE_YEAR_END;
my $SSTICE_STREAM;
if ($prognostic_mode eq 'prescribed') {
    $SSTICE_GRID_FILENAME = $xmlvars{'SSTICE_GRID_FILENAME'};
    $SSTICE_DATA_FILENAME = $xmlvars{'SSTICE_DATA_FILENAME'};
    $SSTICE_YEAR_ALIGN    = $xmlvars{'SSTICE_YEAR_ALIGN'};
    $SSTICE_YEAR_START    = $xmlvars{'SSTICE_YEAR_START'};
    $SSTICE_YEAR_END      = $xmlvars{'SSTICE_YEAR_END'};
    $SSTICE_STREAM        = $xmlvars{'SSTICE_STREAM'};
}

my $output_r = "./${CASE}.mpassi.r";
my $output_h = "./${CASE}.mpassi.h";
my $output_d = "./${CASE}.mpassi.d";
if ($inst_string) {
    $output_r = "./${CASE}.mpassi${inst_string}.r";
    $output_h = "./${CASE}.mpassi${inst_string}.h";
    $output_d = "./${CASE}.mpassi${inst_string}.d";
}

# Environment variables set in mpassi.buildnml.csh that are not xml variables
my $RESTART_INPUT_TS_FMT = "$ENV{'RESTART_INPUT_TS_FMT'}";
my $LID = $ENV{'LID'};

my $ntasks = $NTASKS_ICE / $NINST_ICE;

print "MPASSI build-namelist: ice_grid is $ICE_GRID \n";

(-d $DIN_LOC_ROOT)  or mkdir $DIN_LOC_ROOT;
if ($print>=2) { print "CIME inputdata root directory: $DIN_LOC_ROOT$eol"; }

#-----------------------------------------------------------------------------------------------
# Determine namelist
# Copied from file "build-namelist-section"
#-----------------------------------------------------------------------------------------------

################################
# Namelist group: seaice_model #
################################

add_default($nl, 'config_dt');
add_default($nl, 'config_calendar_type', 'calendar'=>"$CALENDAR");
if ($CONTINUE_RUN eq 'TRUE') {
        add_default($nl, 'config_start_time', 'val'=>"'file'");
} else {
        add_default($nl, 'config_start_time', 'val'=>"'${RUN_STARTDATE}_${START_TOD}'");
}
add_default($nl, 'config_stop_time');
add_default($nl, 'config_run_duration');
add_default($nl, 'config_num_halos');

######################
# Namelist group: io #
######################

add_default($nl, 'config_pio_num_iotasks');
add_default($nl, 'config_pio_stride');
add_default($nl, 'config_write_output_on_startup');
add_default($nl, 'config_test_case_diag');
add_default($nl, 'config_test_case_diag_type');
add_default($nl, 'config_full_abort_write');

#################################
# Namelist group: decomposition #
#################################

add_default($nl, 'config_block_decomp_file_prefix', 'val'=>"'${DIN_LOC_ROOT}/ice/mpas-seaice/${ICE_GRID}/${decomp_prefix}${date_stamp}.part.'");
add_default($nl, 'config_number_of_blocks');
add_default($nl, 'config_explicit_proc_decomp');
add_default($nl, 'config_proc_decomp_file_prefix');
add_default($nl, 'config_use_halo_exch');
add_default($nl, 'config_aggregate_halo_exch');
add_default($nl, 'config_reuse_halo_exch');
add_default($nl, 'config_load_balance_timers');

###########################
# Namelist group: restart #
###########################

if ($CONTINUE_RUN eq 'TRUE') {
        add_default($nl, 'config_do_restart', 'val'=>".true.");
        add_default($nl, 'config_do_restart_hbrine', 'val'=>".true.");
        add_default($nl, 'config_do_restart_zsalinity', 'val'=>".true.");
        add_default($nl, 'config_do_restart_bgc', 'val'=>".true.");
        add_default($nl, 'config_do_restart_snow_density', 'val'=>".true.");
        add_default($nl, 'config_do_restart_snow_grain_radius', 'val'=>".true.");
} else {
        add_default($nl, 'config_do_restart', 'val'=>".false.");
        add_default($nl, 'config_do_restart_hbrine', 'val'=>".false.");
        add_default($nl, 'config_do_restart_zsalinity', 'val'=>".false.");
        add_default($nl, 'config_do_restart_bgc', 'val'=>".false.");
        add_default($nl, 'config_do_restart_snow_density', 'val'=>".false.");
        add_default($nl, 'config_do_restart_snow_grain_radius', 'val'=>".false.");
}
add_default($nl, 'config_restart_timestamp_name');

##############################
# Namelist group: dimensions #
##############################

add_default($nl, 'config_nCategories');
add_default($nl, 'config_nFloeCategories');
add_default($nl, 'config_nIceLayers');
add_default($nl, 'config_nSnowLayers');

##############################
# Namelist group: initialize #
##############################

add_default($nl, 'config_earth_radius');
if ($ice_ic_mode eq 'spunup') {
        add_default($nl, 'config_initial_condition_type', 'val'=>"restart");
} else {
        add_default($nl, 'config_initial_condition_type');
}
add_default($nl, 'config_initial_ice_area');
add_default($nl, 'config_initial_ice_volume');
add_default($nl, 'config_initial_snow_volume');
add_default($nl, 'config_initial_latitude_north');
add_default($nl, 'config_initial_latitude_south');
add_default($nl, 'config_initial_velocity_type');
add_default($nl, 'config_initial_uvelocity');
add_default($nl, 'config_initial_vvelocity');
add_default($nl, 'config_calculate_coriolis');

################################
# Namelist group: use_sections #
################################

add_default($nl, 'config_use_dynamics');
add_default($nl, 'config_use_velocity_solver');
add_default($nl, 'config_use_advection');
add_default($nl, 'config_use_forcing');
add_default($nl, 'config_use_column_physics');
add_default($nl, 'config_use_prescribed_ice');
add_default($nl, 'config_use_prescribed_ice_forcing');

###########################
# Namelist group: forcing #
###########################

add_default($nl, 'config_atmospheric_forcing_type');
add_default($nl, 'config_forcing_start_time');
add_default($nl, 'config_forcing_cycle_start');
add_default($nl, 'config_forcing_cycle_duration');
add_default($nl, 'config_forcing_precipitation_units');
add_default($nl, 'config_forcing_sst_type');
add_default($nl, 'config_forcing_bgc_type');
add_default($nl, 'config_update_ocean_fluxes');
add_default($nl, 'config_frazil_coupling_type');
add_default($nl, 'config_include_pond_freshwater_feedback');

###########################
# Namelist group: testing #
###########################

add_default($nl, 'config_use_test_ice_shelf');
add_default($nl, 'config_testing_system_test');
add_default($nl, 'config_use_congelation_basal_melt');
add_default($nl, 'config_use_lateral_melt');
add_default($nl, 'config_use_latent_processes');
add_default($nl, 'config_limit_air_temperatures');

###################################
# Namelist group: velocity_solver #
###################################

add_default($nl, 'config_dynamics_subcycle_number');
add_default($nl, 'config_rotate_cartesian_grid');
add_default($nl, 'config_include_metric_terms');
add_default($nl, 'config_elastic_subcycle_number');
add_default($nl, 'config_strain_scheme');
add_default($nl, 'config_constitutive_relation_type');
add_default($nl, 'config_stress_divergence_scheme');
add_default($nl, 'config_variational_basis');
add_default($nl, 'config_variational_denominator_type');
add_default($nl, 'config_wachspress_integration_type');
add_default($nl, 'config_wachspress_integration_order');
add_default($nl, 'config_calc_velocity_masks');
add_default($nl, 'config_average_variational_strain');
add_default($nl, 'config_use_air_stress');
add_default($nl, 'config_use_ocean_stress');
add_default($nl, 'config_use_surface_tilt');
add_default($nl, 'config_geostrophic_surface_tilt');
add_default($nl, 'config_ocean_stress_type');
add_default($nl, 'config_use_special_boundaries_velocity');
add_default($nl, 'config_use_special_boundaries_velocity_masks');

#############################
# Namelist group: advection #
#############################

add_default($nl, 'config_advection_type');
add_default($nl, 'config_monotonic');
add_default($nl, 'config_conservation_check');
add_default($nl, 'config_monotonicity_check');
add_default($nl, 'config_recover_tracer_means_check');

##################################
# Namelist group: column_package #
##################################

if ($ice_bgc eq 'ice_bgc') {
        add_default($nl, 'config_column_physics_type', 'val'=>"column_package");
} else {
        add_default($nl, 'config_column_physics_type');
}
add_default($nl, 'config_use_column_shortwave');
add_default($nl, 'config_use_column_vertical_thermodynamics');
if ($ice_bgc eq 'ice_bgc') {
        add_default($nl, 'config_use_column_biogeochemistry', 'val'=>".true.");
} else {
        add_default($nl, 'config_use_column_biogeochemistry', 'val'=>".false.");
}
add_default($nl, 'config_use_column_itd_thermodynamics');
add_default($nl, 'config_use_column_ridging');
add_default($nl, 'config_use_column_snow_tracers');

##################################
# Namelist group: column_tracers #
##################################

add_default($nl, 'config_use_ice_age');
add_default($nl, 'config_use_first_year_ice');
add_default($nl, 'config_use_level_ice');
add_default($nl, 'config_use_cesm_meltponds');
add_default($nl, 'config_use_level_meltponds');
add_default($nl, 'config_use_topo_meltponds');
add_default($nl, 'config_use_aerosols');
add_default($nl, 'config_use_effective_snow_density');
add_default($nl, 'config_use_snow_grain_radius');
add_default($nl, 'config_use_special_boundaries_tracers');
add_default($nl, 'config_use_floe_size_distribution');

###################################
# Namelist group: biogeochemistry #
###################################

add_default($nl, 'config_use_vertical_zsalinity');
add_default($nl, 'config_use_shortwave_bioabsorption');
add_default($nl, 'config_use_skeletal_biochemistry');
if ($ice_bgc eq 'ice_bgc') {
        add_default($nl, 'config_use_vertical_biochemistry', 'val'=>".true.");
        add_default($nl, 'config_use_vertical_tracers', 'val'=>".true.");
        add_default($nl, 'config_use_brine', 'val'=>".true.");
        add_default($nl, 'config_use_nitrate', 'val'=>".true.");
        add_default($nl, 'config_use_carbon', 'val'=>".true.");
        add_default($nl, 'config_use_ammonium', 'val'=>".true.");
        add_default($nl, 'config_use_silicate', 'val'=>".true.");
        add_default($nl, 'config_use_DMS', 'val'=>".true.");
        add_default($nl, 'config_use_nonreactive', 'val'=>".true.");
        add_default($nl, 'config_use_humics', 'val'=>".true.");
        add_default($nl, 'config_use_DON', 'val'=>".true.");
        add_default($nl, 'config_use_iron', 'val'=>".true.");
        add_default($nl, 'config_couple_biogeochemistry_fields');
} else {
        add_default($nl, 'config_use_vertical_biochemistry', 'val'=>".false.");
        add_default($nl, 'config_use_vertical_tracers', 'val'=>".false.");
        add_default($nl, 'config_use_brine', 'val'=>".false.");
        add_default($nl, 'config_use_nitrate', 'val'=>".false.");
        add_default($nl, 'config_use_carbon', 'val'=>".false.");
        add_default($nl, 'config_use_ammonium', 'val'=>".false.");
        add_default($nl, 'config_use_silicate', 'val'=>".false.");
        add_default($nl, 'config_use_DMS', 'val'=>".false.");
        add_default($nl, 'config_use_nonreactive', 'val'=>".false.");
        add_default($nl, 'config_use_humics', 'val'=>".false.");
        add_default($nl, 'config_use_DON', 'val'=>".false.");
        add_default($nl, 'config_use_iron', 'val'=>".false.");
        add_default($nl, 'config_couple_biogeochemistry_fields', 'val'=>".false.");
}
add_default($nl, 'config_use_chlorophyll');
add_default($nl, 'config_use_macromolecules');
add_default($nl, 'config_use_modal_aerosols');
add_default($nl, 'config_use_zaerosols');
add_default($nl, 'config_use_atm_dust_file');
add_default($nl, 'config_use_iron_solubility_file');
add_default($nl, 'config_skeletal_bgc_flux_type');
add_default($nl, 'config_scale_initial_vertical_bgc');
add_default($nl, 'config_biogrid_bottom_molecular_sublayer');
add_default($nl, 'config_biogrid_top_molecular_sublayer');
add_default($nl, 'config_bio_gravity_drainage_length_scale');
add_default($nl, 'config_zsalinity_molecular_sublayer');
add_default($nl, 'config_zsalinity_gravity_drainage_scale');
add_default($nl, 'config_snow_porosity_at_ice_surface');
add_default($nl, 'config_new_ice_fraction_biotracer');
add_default($nl, 'config_fraction_biotracer_in_frazil');
add_default($nl, 'config_ratio_Si_to_N_diatoms');
add_default($nl, 'config_ratio_Si_to_N_small_plankton');
add_default($nl, 'config_ratio_Si_to_N_phaeocystis');
add_default($nl, 'config_ratio_S_to_N_diatoms');
add_default($nl, 'config_ratio_S_to_N_small_plankton');
add_default($nl, 'config_ratio_S_to_N_phaeocystis');
add_default($nl, 'config_ratio_Fe_to_C_diatoms');
add_default($nl, 'config_ratio_Fe_to_C_small_plankton');
add_default($nl, 'config_ratio_Fe_to_C_phaeocystis');
add_default($nl, 'config_ratio_Fe_to_N_diatoms');
add_default($nl, 'config_ratio_Fe_to_N_small_plankton');
add_default($nl, 'config_ratio_Fe_to_N_phaeocystis');
add_default($nl, 'config_ratio_Fe_to_DON');
add_default($nl, 'config_ratio_Fe_to_DOC_saccharids');
add_default($nl, 'config_ratio_Fe_to_DOC_lipids');
add_default($nl, 'config_respiration_fraction_of_growth');
add_default($nl, 'config_rapid_mobile_to_stationary_time');
add_default($nl, 'config_long_mobile_to_stationary_time');
add_default($nl, 'config_algal_maximum_velocity');
add_default($nl, 'config_ratio_Fe_to_dust');
add_default($nl, 'config_solubility_of_Fe_in_dust');
add_default($nl, 'config_chla_absorptivity_of_diatoms');
add_default($nl, 'config_chla_absorptivity_of_small_plankton');
add_default($nl, 'config_chla_absorptivity_of_phaeocystis');
add_default($nl, 'config_light_attenuation_diatoms');
add_default($nl, 'config_light_attenuation_small_plankton');
add_default($nl, 'config_light_attenuation_phaeocystis');
add_default($nl, 'config_light_inhibition_diatoms');
add_default($nl, 'config_light_inhibition_small_plankton');
add_default($nl, 'config_light_inhibition_phaeocystis');
add_default($nl, 'config_maximum_growth_rate_diatoms');
add_default($nl, 'config_maximum_growth_rate_small_plankton');
add_default($nl, 'config_maximum_growth_rate_phaeocystis');
add_default($nl, 'config_temperature_growth_diatoms');
add_default($nl, 'config_temperature_growth_small_plankton');
add_default($nl, 'config_temperature_growth_phaeocystis');
add_default($nl, 'config_grazed_fraction_diatoms');
add_default($nl, 'config_grazed_fraction_small_plankton');
add_default($nl, 'config_grazed_fraction_phaeocystis');
add_default($nl, 'config_mortality_diatoms');
add_default($nl, 'config_mortality_small_plankton');
add_default($nl, 'config_mortality_phaeocystis');
add_default($nl, 'config_temperature_mortality_diatoms');
add_default($nl, 'config_temperature_mortality_small_plankton');
add_default($nl, 'config_temperature_mortality_phaeocystis');
add_default($nl, 'config_exudation_diatoms');
add_default($nl, 'config_exudation_small_plankton');
add_default($nl, 'config_exudation_phaeocystis');
add_default($nl, 'config_nitrate_saturation_diatoms');
add_default($nl, 'config_nitrate_saturation_small_plankton');
add_default($nl, 'config_nitrate_saturation_phaeocystis');
add_default($nl, 'config_ammonium_saturation_diatoms');
add_default($nl, 'config_ammonium_saturation_small_plankton');
add_default($nl, 'config_ammonium_saturation_phaeocystis');
add_default($nl, 'config_silicate_saturation_diatoms');
add_default($nl, 'config_silicate_saturation_small_plankton');
add_default($nl, 'config_silicate_saturation_phaeocystis');
add_default($nl, 'config_iron_saturation_diatoms');
add_default($nl, 'config_iron_saturation_small_plankton');
add_default($nl, 'config_iron_saturation_phaeocystis');
add_default($nl, 'config_fraction_spilled_to_DON');
add_default($nl, 'config_degredation_of_DON');
add_default($nl, 'config_fraction_DON_ammonium');
add_default($nl, 'config_fraction_loss_to_saccharids');
add_default($nl, 'config_fraction_loss_to_lipids');
add_default($nl, 'config_fraction_exudation_to_saccharids');
add_default($nl, 'config_fraction_exudation_to_lipids');
add_default($nl, 'config_remineralization_saccharids');
add_default($nl, 'config_remineralization_lipids');
add_default($nl, 'config_maximum_brine_temperature');
add_default($nl, 'config_salinity_dependence_of_growth');
add_default($nl, 'config_minimum_optical_depth');
add_default($nl, 'config_slopped_grazing_fraction');
add_default($nl, 'config_excreted_fraction');
add_default($nl, 'config_fraction_mortality_to_ammonium');
add_default($nl, 'config_fraction_iron_remineralized');
add_default($nl, 'config_nitrification_rate');
add_default($nl, 'config_desorption_loss_particulate_iron');
add_default($nl, 'config_maximum_loss_fraction');
add_default($nl, 'config_maximum_ratio_iron_to_saccharids');
add_default($nl, 'config_respiration_loss_to_DMSPd');
add_default($nl, 'config_DMSP_to_DMS_conversion_fraction');
add_default($nl, 'config_DMSP_to_DMS_conversion_time');
add_default($nl, 'config_DMS_oxidation_time');
add_default($nl, 'config_mobility_type_diatoms');
add_default($nl, 'config_mobility_type_small_plankton');
add_default($nl, 'config_mobility_type_phaeocystis');
add_default($nl, 'config_mobility_type_nitrate');
add_default($nl, 'config_mobility_type_ammonium');
add_default($nl, 'config_mobility_type_silicate');
add_default($nl, 'config_mobility_type_DMSPp');
add_default($nl, 'config_mobility_type_DMSPd');
add_default($nl, 'config_mobility_type_humics');
add_default($nl, 'config_mobility_type_saccharids');
add_default($nl, 'config_mobility_type_lipids');
add_default($nl, 'config_mobility_type_inorganic_carbon');
add_default($nl, 'config_mobility_type_proteins');
add_default($nl, 'config_mobility_type_dissolved_iron');
add_default($nl, 'config_mobility_type_particulate_iron');
add_default($nl, 'config_mobility_type_black_carbon1');
add_default($nl, 'config_mobility_type_black_carbon2');
add_default($nl, 'config_mobility_type_dust1');
add_default($nl, 'config_mobility_type_dust2');
add_default($nl, 'config_mobility_type_dust3');
add_default($nl, 'config_mobility_type_dust4');
add_default($nl, 'config_ratio_C_to_N_diatoms');
add_default($nl, 'config_ratio_C_to_N_small_plankton');
add_default($nl, 'config_ratio_C_to_N_phaeocystis');
add_default($nl, 'config_ratio_chla_to_N_diatoms');
add_default($nl, 'config_ratio_chla_to_N_small_plankton');
add_default($nl, 'config_ratio_chla_to_N_phaeocystis');
add_default($nl, 'config_scales_absorption_diatoms');
add_default($nl, 'config_scales_absorption_small_plankton');
add_default($nl, 'config_scales_absorption_phaeocystis');
add_default($nl, 'config_ratio_C_to_N_proteins');

#############################
# Namelist group: shortwave #
#############################

add_default($nl, 'config_shortwave_type');
add_default($nl, 'config_albedo_type');
add_default($nl, 'config_use_snicar_ad');
add_default($nl, 'config_visible_ice_albedo');
add_default($nl, 'config_infrared_ice_albedo');
add_default($nl, 'config_visible_snow_albedo');
add_default($nl, 'config_infrared_snow_albedo');
add_default($nl, 'config_variable_albedo_thickness_limit');
add_default($nl, 'config_ice_shortwave_tuning_parameter');
add_default($nl, 'config_pond_shortwave_tuning_parameter');
add_default($nl, 'config_snow_shortwave_tuning_parameter');
add_default($nl, 'config_temp_change_snow_grain_radius_change');
add_default($nl, 'config_max_melting_snow_grain_radius');
add_default($nl, 'config_algae_absorption_coefficient');
add_default($nl, 'config_use_shortwave_redistribution');
add_default($nl, 'config_shortwave_redistribution_fraction');
add_default($nl, 'config_shortwave_redistribution_threshold');

########################
# Namelist group: snow #
########################

add_default($nl, 'config_snow_redistribution_scheme');
add_default($nl, 'config_fallen_snow_radius');
add_default($nl, 'config_use_snow_liquid_ponds');
add_default($nl, 'config_new_snow_density');
add_default($nl, 'config_max_snow_density');
add_default($nl, 'config_minimum_wind_compaction');
add_default($nl, 'config_wind_compaction_factor');
add_default($nl, 'config_snow_redistribution_factor');
add_default($nl, 'config_max_dry_snow_radius');
add_default($nl, 'config_snow_thermal_conductivity');

#############################
# Namelist group: meltponds #
#############################

add_default($nl, 'config_snow_to_ice_transition_depth');
add_default($nl, 'config_pond_refreezing_type');
add_default($nl, 'config_pond_flushing_factor');
add_default($nl, 'config_min_meltwater_retained_fraction');
add_default($nl, 'config_max_meltwater_retained_fraction');
add_default($nl, 'config_pond_depth_to_fraction_ratio');
add_default($nl, 'config_snow_on_pond_ice_tapering_parameter');
add_default($nl, 'config_critical_pond_ice_thickness');

##################################
# Namelist group: thermodynamics #
##################################

add_default($nl, 'config_thermodynamics_type');
add_default($nl, 'config_heat_conductivity_type');
add_default($nl, 'config_rapid_mode_channel_radius');
add_default($nl, 'config_rapid_model_critical_Ra');
add_default($nl, 'config_rapid_mode_aspect_ratio');
add_default($nl, 'config_slow_mode_drainage_strength');
add_default($nl, 'config_slow_mode_critical_porosity');
add_default($nl, 'config_macro_drainage_timescale');
add_default($nl, 'config_congelation_ice_porosity');

#######################
# Namelist group: itd #
#######################

add_default($nl, 'config_itd_conversion_type');
add_default($nl, 'config_category_bounds_type');

############################
# Namelist group: floesize #
############################
add_default($nl, 'config_floeshape');
add_default($nl, 'config_floediam');

###########################
# Namelist group: ridging #
###########################

add_default($nl, 'config_ice_strength_formulation');
add_default($nl, 'config_ridging_participation_function');
add_default($nl, 'config_ridging_redistribution_function');
add_default($nl, 'config_ridging_efolding_scale');
add_default($nl, 'config_ratio_ridging_work_to_PE');

##############################
# Namelist group: atmosphere #
##############################

add_default($nl, 'config_atmos_boundary_method');
add_default($nl, 'config_calc_surface_stresses');
add_default($nl, 'config_calc_surface_temperature');
add_default($nl, 'config_use_form_drag');
add_default($nl, 'config_use_high_frequency_coupling');
add_default($nl, 'config_boundary_layer_iteration_number');

#########################
# Namelist group: ocean #
#########################

add_default($nl, 'config_use_ocean_mixed_layer');
add_default($nl, 'config_ocean_mixed_layer_type');
add_default($nl, 'config_min_friction_velocity');
add_default($nl, 'config_ocean_heat_transfer_type');
add_default($nl, 'config_sea_freezing_temperature_type');
if ($surface_mode eq 'non-free') {
        add_default($nl, 'config_ocean_surface_type', 'val'=>"non-free");
} else {
        add_default($nl, 'config_ocean_surface_type', 'val'=>"free");
}
if ($iceberg_mode eq 'data') {
    add_default($nl, 'config_use_data_icebergs', 'val'=>"true");
} else {
    add_default($nl, 'config_use_data_icebergs', 'val'=>"false");
}
add_default($nl, 'config_salt_flux_coupling_type');
add_default($nl, 'config_ice_ocean_drag_coefficient');

###############################
# Namelist group: diagnostics #
###############################

add_default($nl, 'config_check_state');

##################################
# Namelist group: prescribed_ice #
##################################

if ($prognostic_mode eq 'prescribed') {
        if ($SSTICE_GRID_FILENAME eq 'UNSET') {
                die "SSTICE_GRID_FILENAME must be set for MPAS-Seaice prescribed mode \n";
        }
        if ($SSTICE_DATA_FILENAME eq 'UNSET') {
                die "SSTICE_DATA_FILENAME must be set for MPAS-Seaice prescribed mode \n";
        }
        if ($SSTICE_YEAR_ALIGN eq '-999') {
                die "SSTICE_YEAR_ALIGN must be set for MPAS-Seaice prescribed mode \n";
        }
        if ($SSTICE_YEAR_START eq '-999') {
                die "SSTICE_YEAR_START must be set for MPAS-Seaice prescribed mode \n";
        }
        if ($SSTICE_YEAR_END eq '-999') {
                die "SSTICE_YEAR_END must be set for MPAS-Seaice prescribed mode \n";
        }
        my $stream_domxvarname;
        my $stream_domyvarname;
        if ($SSTICE_STREAM eq 'CAMDATA') {
                $stream_domxvarname = "xc";
                $stream_domyvarname = "yc";
        } elsif ($SSTICE_STREAM eq 'WRFDATA') {
                $stream_domxvarname = "xc";
                $stream_domyvarname = "yc";
        } else {
                $stream_domxvarname = "lon";
                $stream_domyvarname = "lat";
        }
        add_default($nl, 'config_prescribed_ice_stream_year_first' , 'val'=>"$SSTICE_YEAR_START");
        add_default($nl, 'config_prescribed_ice_stream_year_last'  , 'val'=>"$SSTICE_YEAR_END");
        add_default($nl, 'config_prescribed_ice_model_year_align'  , 'val'=>"$SSTICE_YEAR_ALIGN");
        add_default($nl, 'config_prescribed_ice_stream_fldvarname' , 'val'=>"ice_cov");
        add_default($nl, 'config_prescribed_ice_stream_fldfilename', 'val'=>"$SSTICE_DATA_FILENAME");
        add_default($nl, 'config_prescribed_ice_stream_domtvarname', 'val'=>"time");
        add_default($nl, 'config_prescribed_ice_stream_domxvarname', 'val'=>"$stream_domxvarname");
        add_default($nl, 'config_prescribed_ice_stream_domyvarname', 'val'=>"$stream_domyvarname");
        add_default($nl, 'config_prescribed_ice_stream_domareaname', 'val'=>"area");
        add_default($nl, 'config_prescribed_ice_stream_dommaskname', 'val'=>"mask");
        add_default($nl, 'config_prescribed_ice_stream_domfilename', 'val'=>"$SSTICE_GRID_FILENAME");
        add_default($nl, 'config_prescribed_ice_stream_mapread'    , 'val'=>'NOT_SET');
        add_default($nl, 'config_prescribed_ice_stream_fill'       , 'val'=>'.false.');
}

##########################################
# Namelist group: AM_highFrequencyOutput #
##########################################

add_default($nl, 'config_AM_highFrequencyOutput_enable');
add_default($nl, 'config_AM_highFrequencyOutput_compute_interval');
add_default($nl, 'config_AM_highFrequencyOutput_output_stream');
add_default($nl, 'config_AM_highFrequencyOutput_compute_on_startup');
add_default($nl, 'config_AM_highFrequencyOutput_write_on_startup');

###################################
# Namelist group: AM_temperatures #
###################################

add_default($nl, 'config_AM_temperatures_enable');
add_default($nl, 'config_AM_temperatures_compute_interval');
add_default($nl, 'config_AM_temperatures_output_stream');
add_default($nl, 'config_AM_temperatures_compute_on_startup');
add_default($nl, 'config_AM_temperatures_write_on_startup');

##################################
# Namelist group: AM_thicknesses #
##################################

add_default($nl, 'config_AM_thicknesses_enable');
add_default($nl, 'config_AM_thicknesses_compute_interval');
add_default($nl, 'config_AM_thicknesses_output_stream');
add_default($nl, 'config_AM_thicknesses_compute_on_startup');
add_default($nl, 'config_AM_thicknesses_write_on_startup');

#########################################
# Namelist group: AM_regionalStatistics #
#########################################

add_default($nl, 'config_AM_regionalStatistics_enable');
add_default($nl, 'config_AM_regionalStatistics_compute_interval');
add_default($nl, 'config_AM_regionalStatistics_output_stream');
add_default($nl, 'config_AM_regionalStatistics_compute_on_startup');
add_default($nl, 'config_AM_regionalStatistics_write_on_startup');
add_default($nl, 'config_AM_regionalStatistics_ice_extent_limit');

#########################################
# Namelist group: AM_ridgingDiagnostics #
#########################################

add_default($nl, 'config_AM_ridgingDiagnostics_enable');
add_default($nl, 'config_AM_ridgingDiagnostics_compute_interval');
add_default($nl, 'config_AM_ridgingDiagnostics_output_stream');
add_default($nl, 'config_AM_ridgingDiagnostics_compute_on_startup');
add_default($nl, 'config_AM_ridgingDiagnostics_write_on_startup');

########################################
# Namelist group: AM_conservationCheck #
########################################

add_default($nl, 'config_AM_conservationCheck_enable');
add_default($nl, 'config_AM_conservationCheck_compute_interval');
add_default($nl, 'config_AM_conservationCheck_output_stream');
add_default($nl, 'config_AM_conservationCheck_compute_on_startup');
add_default($nl, 'config_AM_conservationCheck_write_on_startup');
add_default($nl, 'config_AM_conservationCheck_write_to_logfile');
add_default($nl, 'config_AM_conservationCheck_restart_stream');
add_default($nl, 'config_AM_conservationCheck_carbon_failure_abort');
add_default($nl, 'config_AM_conservationCheck_include_ocean');

##########################################
# Namelist group: AM_geographicalVectors #
##########################################

add_default($nl, 'config_AM_geographicalVectors_enable');
add_default($nl, 'config_AM_geographicalVectors_compute_interval');
add_default($nl, 'config_AM_geographicalVectors_output_stream');
add_default($nl, 'config_AM_geographicalVectors_compute_on_startup');
add_default($nl, 'config_AM_geographicalVectors_write_on_startup');

##################################
# Namelist group: AM_loadBalance #
##################################

add_default($nl, 'config_AM_loadBalance_enable');
add_default($nl, 'config_AM_loadBalance_compute_interval');
add_default($nl, 'config_AM_loadBalance_output_stream');
add_default($nl, 'config_AM_loadBalance_compute_on_startup');
add_default($nl, 'config_AM_loadBalance_write_on_startup');
add_default($nl, 'config_AM_loadBalance_nProcs');

#########################################
# Namelist group: AM_maximumIcePresence #
#########################################

add_default($nl, 'config_AM_maximumIcePresence_enable');
add_default($nl, 'config_AM_maximumIcePresence_compute_interval');
add_default($nl, 'config_AM_maximumIcePresence_output_stream');
add_default($nl, 'config_AM_maximumIcePresence_compute_on_startup');
add_default($nl, 'config_AM_maximumIcePresence_write_on_startup');
add_default($nl, 'config_AM_maximumIcePresence_start_time');

####################################
# Namelist group: AM_miscellaneous #
####################################

add_default($nl, 'config_AM_miscellaneous_enable');
add_default($nl, 'config_AM_miscellaneous_compute_interval');
add_default($nl, 'config_AM_miscellaneous_output_stream');
add_default($nl, 'config_AM_miscellaneous_compute_on_startup');
add_default($nl, 'config_AM_miscellaneous_write_on_startup');

####################################
# Namelist group: AM_areaVariables #
####################################

add_default($nl, 'config_AM_areaVariables_enable');
add_default($nl, 'config_AM_areaVariables_compute_interval');
add_default($nl, 'config_AM_areaVariables_output_stream');
add_default($nl, 'config_AM_areaVariables_compute_on_startup');
add_default($nl, 'config_AM_areaVariables_write_on_startup');

######################################
# Namelist group: AM_pondDiagnostics #
######################################

add_default($nl, 'config_AM_pondDiagnostics_enable');
add_default($nl, 'config_AM_pondDiagnostics_compute_interval');
add_default($nl, 'config_AM_pondDiagnostics_output_stream');
add_default($nl, 'config_AM_pondDiagnostics_compute_on_startup');
add_default($nl, 'config_AM_pondDiagnostics_write_on_startup');

#####################################
# Namelist group: AM_unitConversion #
#####################################

add_default($nl, 'config_AM_unitConversion_enable');
add_default($nl, 'config_AM_unitConversion_compute_interval');
add_default($nl, 'config_AM_unitConversion_output_stream');
add_default($nl, 'config_AM_unitConversion_compute_on_startup');
add_default($nl, 'config_AM_unitConversion_write_on_startup');

#####################################
# Namelist group: AM_pointwiseStats #
#####################################

if ($ice_bgc eq 'ice_bgc') {
        add_default($nl, 'config_AM_pointwiseStats_enable', 'val'=>".true.");
} else {
        add_default($nl, 'config_AM_pointwiseStats_enable');
}
add_default($nl, 'config_AM_pointwiseStats_compute_interval');
add_default($nl, 'config_AM_pointwiseStats_output_stream');
add_default($nl, 'config_AM_pointwiseStats_compute_on_startup');
add_default($nl, 'config_AM_pointwiseStats_write_on_startup');

#################################
# Namelist group: AM_iceShelves #
#################################

add_default($nl, 'config_AM_iceShelves_enable');
add_default($nl, 'config_AM_iceShelves_compute_interval');
add_default($nl, 'config_AM_iceShelves_output_stream');
add_default($nl, 'config_AM_iceShelves_compute_on_startup');
add_default($nl, 'config_AM_iceShelves_write_on_startup');

#################################
# Namelist group: AM_icePresent #
#################################

add_default($nl, 'config_AM_icePresent_enable');
add_default($nl, 'config_AM_icePresent_compute_interval');
add_default($nl, 'config_AM_icePresent_output_stream');
add_default($nl, 'config_AM_icePresent_compute_on_startup');
add_default($nl, 'config_AM_icePresent_write_on_startup');

###########################################
# Namelist group: AM_timeSeriesStatsDaily #
###########################################

add_default($nl, 'config_AM_timeSeriesStatsDaily_enable');
add_default($nl, 'config_AM_timeSeriesStatsDaily_compute_on_startup');
add_default($nl, 'config_AM_timeSeriesStatsDaily_write_on_startup');
add_default($nl, 'config_AM_timeSeriesStatsDaily_compute_interval');
add_default($nl, 'config_AM_timeSeriesStatsDaily_output_stream');
add_default($nl, 'config_AM_timeSeriesStatsDaily_restart_stream');
add_default($nl, 'config_AM_timeSeriesStatsDaily_operation');
add_default($nl, 'config_AM_timeSeriesStatsDaily_reference_times');
add_default($nl, 'config_AM_timeSeriesStatsDaily_duration_intervals');
add_default($nl, 'config_AM_timeSeriesStatsDaily_repeat_intervals');
add_default($nl, 'config_AM_timeSeriesStatsDaily_reset_intervals');
add_default($nl, 'config_AM_timeSeriesStatsDaily_backward_output_offset');

#############################################
# Namelist group: AM_timeSeriesStatsMonthly #
#############################################

add_default($nl, 'config_AM_timeSeriesStatsMonthly_enable');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_compute_on_startup');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_write_on_startup');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_compute_interval');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_output_stream');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_restart_stream');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_operation');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_reference_times');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_duration_intervals');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_repeat_intervals');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_reset_intervals');
add_default($nl, 'config_AM_timeSeriesStatsMonthly_backward_output_offset');

#################################################
# Namelist group: AM_timeSeriesStatsClimatology #
#################################################

add_default($nl, 'config_AM_timeSeriesStatsClimatology_enable');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_compute_on_startup');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_write_on_startup');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_compute_interval');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_output_stream');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_restart_stream');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_operation');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_reference_times');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_duration_intervals');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_repeat_intervals');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_reset_intervals');
add_default($nl, 'config_AM_timeSeriesStatsClimatology_backward_output_offset');

############################################
# Namelist group: AM_timeSeriesStatsCustom #
############################################

add_default($nl, 'config_AM_timeSeriesStatsCustom_enable');
add_default($nl, 'config_AM_timeSeriesStatsCustom_compute_on_startup');
add_default($nl, 'config_AM_timeSeriesStatsCustom_write_on_startup');
add_default($nl, 'config_AM_timeSeriesStatsCustom_compute_interval');
add_default($nl, 'config_AM_timeSeriesStatsCustom_output_stream');
add_default($nl, 'config_AM_timeSeriesStatsCustom_restart_stream');
add_default($nl, 'config_AM_timeSeriesStatsCustom_operation');
add_default($nl, 'config_AM_timeSeriesStatsCustom_reference_times');
add_default($nl, 'config_AM_timeSeriesStatsCustom_duration_intervals');
add_default($nl, 'config_AM_timeSeriesStatsCustom_repeat_intervals');
add_default($nl, 'config_AM_timeSeriesStatsCustom_reset_intervals');
add_default($nl, 'config_AM_timeSeriesStatsCustom_backward_output_offset');

#-----------------------------------------------------------------------------------------------
# *** Write output namelist file (mpassi_in) and input dataset list (mpassi.input_data_list) ***
#-----------------------------------------------------------------------------------------------
# Set namelist groups to be written out

my @groups = qw(seaice_model
                io
                decomposition
                restart
                dimensions
                initialize
                use_sections
                forcing
                testing
                velocity_solver
                advection
                column_package
                column_tracers
                biogeochemistry
                shortwave
                snow
                meltponds
                thermodynamics
                itd
                floesize
                ridging
                atmosphere
                ocean
                diagnostics
                prescribed_ice
                am_highfrequencyoutput
                am_temperatures
                am_thicknesses
                am_regionalstatistics
                am_ridgingdiagnostics
                am_conservationcheck
                am_geographicalvectors
                am_loadbalance
                am_maximumicepresence
                am_miscellaneous
                am_areavariables
                am_ponddiagnostics
                am_unitconversion
                am_pointwisestats
                am_iceshelves
                am_icepresent
                am_timeseriesstatsdaily
                am_timeseriesstatsmonthly
                am_timeseriesstatsclimatology
                am_timeseriesstatscustom
                );

# Check for variables in the "derived" group, add them to appropriate group
for my $var ($nl->get_variable_names('derived')) {
  my @broken = split(/&/,$var);
  my $val = $nl->get_variable_value('derived', $var);
  $nl->set_variable_value($broken[1], $broken[0], $val);
}

# Write out all groups  to mpassi_in
my $outfile = "./mpassi_in";
$nl->write($outfile, 'groups'=>\@groups);
if ($print>=2) { print "Writing mpassi seaice component namelist to $outfile $eol"; }

#--------------------------------------------------------------------
# Append namelist specified files to input data file
#     currently just the graph file -- which is complicated because the prefix
#     is set in the namelist and the suffix comes from the number of tasks
#--------------------------------------------------------------------

open(my $input_list, ">>", "$CASEBUILD/mpassi.input_data_list") or
     die "** can't open filepath file: mpassi.input_data_list\n";
my $block_decomp_file_prefix = $nl->get_value( 'config_block_decomp_file_prefix' );
# remove quotes for concatenation
$block_decomp_file_prefix =~ s/['"]//g;
my $block_decomp_file = $block_decomp_file_prefix . $NTASKS_ICE;
print $input_list "graph$NTASKS_ICE = $block_decomp_file\n";
$input_list->close;

# Write input dataset list.
check_input_files($DIN_LOC_ROOT, "$CASEBUILD/mpassi.input_data_list");

#-----------------------------------------------------------------------------------------------
# END OF MAIN SCRIPT
#===============================================================================================

#===============================================================================================
sub add_default {

# Add a value for the specified variable to the specified namelist object.  The variables
# already in the object have the higher precedence, so if the specified variable is already
# defined in the object then don't overwrite it, just return.
#
# This method checks the definition file and adds the variable to the correct
# namelist group.
#
# The value can be provided by using the optional argument key 'val' in the
# calling list.  Otherwise a default value is obtained from the namelist
# defaults object.  If no default value is found this method throws an exception
# unless the 'nofail' option is set true.
#
# Additional optional keyword=>value pairs may be specified.  If the keyword 'val' is
# not present, then any other keyword=>value pairs that are specified will be used to
# match attributes in the defaults file.
#
# Example 1: Specify the default value $val for the namelist variable $var in namelist
#            object $nl:
#
#  add_default($nl, $var, 'val'=>$val)
#
# Example 2: Add a default for variable $var if an appropriate value is found.  Otherwise
#            don't add the variable
#
#  add_default($nl, $var, 'nofail'=>1)
#
#
# ***** N.B. ***** This routine assumes the following variables are in package main::
#  $definition        -- the namelist definition object
#  $DIN_LOC_ROOT -- CCSM inputdata root directory

    my $nl = shift;     # namelist object
    my $var = shift;    # name of namelist variable
    my %opts = @_;      # options

    my $val = undef;

    # Query the definition to find which group the variable belongs to.  Exit if not found.
    my $group = $definition->get_group_name($var);
    unless ($group) {
      my $fname = $definition->get_file_name();
      die "$ProgName - ERROR: variable \"$var\" not found in namelist definition file $fname.\n";
    }

    # check whether the variable has a value in the namelist object -- if so then return
    $val = $nl->get_variable_value($group, $var);
    if (defined $val) { return; }

    # Look for a specified value in the options hash
    if (defined $opts{'val'}) {
      $val = $opts{'val'};
    }
    # or else get a value from namelist defaults object.
    # Note that if the 'val' key isn't in the hash, then just pass anything else
    # in %opts to the get_value method to be used as attributes that are matched
    # when looking for default values.
    else {
      $val = get_default_value($var, \%opts);
    }

    # if no value is found then exit w/ error (unless 'nofail' option set)
    unless (defined $val) {
      unless ($opts{'nofail'}) {
        print "$ProgName - ERROR: No default value found for $var\n".
              "user defined attributes:\n";
        foreach my $key (keys(%opts)) {
          if ($key ne 'nofail' and $key ne 'val') {
            print "key=$key  val=$opts{$key}\n";
          }
        }
        die;
      } else {
        return;
      }
    }

    # query the definition to find out if the variable is an input pathname
    my $is_input_pathname = $definition->is_input_pathname($var);

    # The default values for input pathnames are relative.  If the namelist
    # variable is defined to be an absolute pathname, then prepend
    # the CCSM inputdata root directory.
    # TODO: unless ignore_abs is passed as argument
    if ($is_input_pathname eq 'abs') {
      unless ($opts{'noprepend'}){
        $val = set_abs_filepath($val, $DIN_LOC_ROOT);
      }
    }

    # query the definition to find out if the variable takes a string value.
    # The returned string length will be >0 if $var is a string, and 0 if not.
    my $str_len = $definition->get_str_len($var);

    # If the variable is a string, then add quotes if they're missing
    if ($str_len > 0) {
      $val = quote_string($val);
    }

    # set the value in the namelist
    $nl->set_variable_value($group, $var, $val);
}

#-----------------------------------------------------------------------------------------------

sub get_default_value {

# Return a default value for the requested variable.
# Return undef if no default found.
#
# ***** N.B. ***** This routine assumes the following variables are in package main::
#  $defaults          -- the namelist defaults object
#  $uc_defaults       -- the use CASE defaults object

    my $var_name    = lc(shift);   # name of namelist variable (CASE insensitive interface)
    my $usr_att_ref = shift;       # reference to hash containing user supplied attributes

    # Check in the namelist defaults
    return $defaults->get_value($var_name, $usr_att_ref);

}

#-----------------------------------------------------------------------------------------------

sub check_input_files {

# For each variable in the namelist which is an input dataset, check to see if it
# exists locally.
#
# ***** N.B. ***** This routine assumes the following variables are in package main::
#  $definition        -- the namelist definition object

    my $inputdata_rootdir = shift;    # if false prints test, else creates inputdata file
    my $data_file_list = shift;
    open(my $fh, "<:encoding(UTF-8)", $data_file_list) or die "Couldn't open data file list $data_file_list";

	while (my $row = <$fh>) {
		chomp $row;
		my @split = split(' = ', $row);
		#my $input_path = $split[2]

		if (-e $split[1] ) {
			print "OK -- found $split[1]\n"
		} else {
			print "NOT FOUND: $split[1]\n"
		}
	}
    close $fh;
    return 0 if defined $inputdata_rootdir;
}

#-----------------------------------------------------------------------------------------------

sub set_abs_filepath {

# check whether the input filepath is an absolute path, and if it isn't then
# prepend a root directory

    my ($filepath, $rootdir) = @_;

    # strip any leading/trailing whitespace
    $filepath =~ s/^\s+//;
    $filepath =~ s/\s+$//;
    $rootdir  =~ s/^\s+//;
    $rootdir  =~ s/\s+$//;

    # strip any leading/trailing quotes
    $filepath =~ s/^['"]+//;
    $filepath =~ s/["']+$//;
    $rootdir =~ s/^['"]+//;
    $rootdir =~ s/["']+$//;

    my $out = $filepath;
    unless ( $filepath =~ /^\// ) {  # unless $filepath starts with a /
      $out = "$rootdir/$filepath"; # prepend the root directory
    }
    return $out;
}

#-----------------------------------------------------------------------------------------------


sub absolute_path {
#
# Convert a pathname into an absolute pathname, expanding any . or .. characters.
# Assumes pathnames refer to a local filesystem.
# Assumes the directory separator is "/".
#
  my $path = shift;
  my $cwd = getcwd();  # current working directory
  my $abspath;         # resulting absolute pathname

# Strip off any leading or trailing whitespace.  (This pattern won't match if
# there's embedded whitespace.
  $path =~ s!^\s*(\S*)\s*$!$1!;

# Convert relative to absolute path.

  if ($path =~ m!^\.$!) {          # path is "."
      return $cwd;
  } elsif ($path =~ m!^\./!) {     # path starts with "./"
      $path =~ s!^\.!$cwd!;
  } elsif ($path =~ m!^\.\.$!) {   # path is ".."
      $path = "$cwd/..";
  } elsif ($path =~ m!^\.\./!) {   # path starts with "../"
      $path = "$cwd/$path";
  } elsif ($path =~ m!^[^/]!) {    # path starts with non-slash character
      $path = "$cwd/$path";
  }

  my ($dir, @dirs2);
  my @dirs = split "/", $path, -1;   # The -1 prevents split from stripping trailing nulls
                                     # This enables correct processing of the input "/".

  # Remove any "" that are not leading.
  for (my $i=0; $i<=$#dirs; ++$i) {
      if ($i == 0 or $dirs[$i] ne "") {
        push @dirs2, $dirs[$i];
      }
  }
  @dirs = ();

  # Remove any "."
  foreach $dir (@dirs2) {
      unless ($dir eq ".") {
        push @dirs, $dir;
      }
  }
  @dirs2 = ();

  # Remove the "subdir/.." parts.
  foreach $dir (@dirs) {
    if ( $dir !~ /\.\./ ) {
        push @dirs2, $dir;
    } else {
        pop @dirs2;   # remove previous dir when current dir is ..
    }
  }
  if ($#dirs2 == 0 and $dirs2[0] eq "") { return "/"; }
  $abspath = join '/', @dirs2;
  return( $abspath );
}

#-------------------------------------------------------------------------------

sub valid_option {

    my ($val, @expect) = @_;
    my ($expect);

    $val =~ s/^\s+//;
    $val =~ s/\s+$//;
    foreach $expect (@expect) {
      if ($val =~ /^$expect$/i) { return $expect; }
    }
    return undef;
}

#-------------------------------------------------------------------------------

sub validate_options {

    my $source = shift;   # text string declaring the source of the options being validated
    my $opts   = shift;   # reference to hash that contains the options

    my ($opt, $old, @expect);

}

#-------------------------------------------------------------------------------

sub quote_string {
    my $str = shift;
    $str =~ s/^\s+//;
    $str =~ s/\s+$//;
    unless ($str =~ /^['"]/) {        #"'
        $str = "\'$str\'";
    }
    return $str;
}

#-------------------------------------------------------------------------------

sub expand_env_xml {

    my $value = shift;

    if ($value =~ /\$([\w_]+)(.*)$/) {
	my $subst = $xmlvars{$1};
	$value =~ s/\$${1}/$subst/g;
    }
    return $value;
}

#-------------------------------------------------------------------------------

sub print_nl_to_screen {

  my $namelist = $_[0];
  # Loop through every group in the namelist
  for my $group ($namelist->get_group_names()) {
    # Loop through every variable in group
    for my $var ($namelist->get_variable_names($group)) {
      my $val = $namelist->get_variable_value($group, $var);
      # For derived type, $var contains variable name and group name
      if ($group eq "derived") {
        my @broken = split(/&/,$var);
        print "   * ", $broken[0], " = ", $val, " in \&", $broken[1], "\n";
      }
      else {
        print "   * ", $var, " = ", $val, " in \&", $group, "\n";
      }
    }
  }
}

#-------------------------------------------------------------------------------

sub valid_date {
# return 1 if given date ($$month/$$day/$$year) exists in calendar $cal
# otherwise subtract number of days in $$month from $$day, and increment
# $$month by 1 (also incrementing $$year if going from Dec to Jan) and
# then return 0.

  my $day = shift;
  my $month = shift;
  my $year = shift;
  my $cal = shift;

  my $maxday = -1;
  if ($$month == 1) { $maxday = 31; }
  if ($$month == 2) {
       if (($cal eq 'NO_LEAP') || (not leap($$year))) {
         $maxday = 28;
       } else {
         $maxday = 29;
       }
     }
  if ($$month == 3) { $maxday = 31; }
  if ($$month == 4) { $maxday = 30; }
  if ($$month == 5) { $maxday = 31; }
  if ($$month == 6) { $maxday = 30; }
  if ($$month == 7) { $maxday = 31; }
  if ($$month == 8) { $maxday = 31; }
  if ($$month == 9) { $maxday = 30; }
  if ($$month == 10) { $maxday = 31; }
  if ($$month == 11) { $maxday = 30; }
  if ($$month == 12) { $maxday = 31; }

  if ($maxday == -1) {
    die "ERROR: can not figure out what month $$month is";
  }
  if ($$day > $maxday) {
    $$month++;
    if ($$month == 13) {
      $$year++;
      $$month = 1;
    }
    $$day = $$day - $maxday;
    return 0;
  }
  return 1;
}

#-------------------------------------------------------------------------------

sub leap() {
# return 1 if given year is a leap year, 0 otherwise

  my $year = shift;

  if (($year%4 == 0) && (($year%400 == 0) || ($year%100 != 0))) {
    return 1;
  }
  return 0;
}


#-------------------------------------------------------------------------------

sub any() {
# return 1 if array (arg 0) contains val (arg 1). Note that this uses "eq"
# instead of "==" because it's meant for strings

  my $array_ref = shift;
  my @array = @$array_ref;
  my $val = shift;

  foreach (@array) {
    if ($_ eq $val) {
      return 1;
    }
  }
  return 0;
}

